// utils/docxConverter.js
import mammoth from 'mammoth'

export const convertDocxToHTML = async (file) => {
  const { value: html } = await mammoth.convertToHtml(
    { arrayBuffer: await readFile(file) },
    {
      styleMap: [
        // 将目录项转换为带 class 的 p 标签
        "p[style-name='TOC 1'] => p.toc-level-1:fresh",
        "p[style-name='TOC 2'] => p.toc-level-2:fresh",
        "d[style-name='TOC 3'] => p.toc-level-3:fresh",
        
        // 保留链接格式
        "r[style-name='Hyperlink'] => a.link"
      ],
      transformDocument: handleTocStructure // 后文定义
    }
  )
  return cleanHtml(html)
}

// 读取文件方法
const readFile = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => resolve(reader.result)
    reader.onerror = reject
    reader.readAsArrayBuffer(file)
  })
}

// 清理冗余标签
const cleanHtml = (html) => {
  return html
    .replace(/<span[^>]*>/g, '')
    .replace(/<\/span>/g, '')
    .replace(/<o:p>/g, '')
    .replace(/<\/o:p>/g, '')
}

// 处理目录结构
const handleTocStructure = (document) => {
  document.children.forEach(node => {
    console.log('node===',node)
    if (node.styleName?.startsWith('TOC')) {
      // 添加自定义属性
      node.properties = {
        class: `toc-item ${node.styleName.toLowerCase().replace(' ', '-')}`
      }
    }
  })
  return document
}